<template>
  <div class="elInputCurrency">
    <span v-if="tooltipModel" class="digit">{{ numberDigit }}</span>
    <el-input
      ref="money"
      v-model="formatValue"
      :size="size"
      :class="{'error':errorType=== true}"
      v-bind="$props"
      validate-event
      maxlength="20"
      :clearable="clearable"
      @clear="emit"
      @blur="handleBlur"
      @focus="handleFocus"
      @input="inputCurrency"
    >
      <template slot="append">
        <slot v-if="$slots.append" name="append" />
      </template>
    </el-input>
  </div>
</template>
<script>
import { props } from './mixin'
export default {
  name: 'Money',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    ...props,
    size: {
      type: String,
      default: ''
    },
    value: {
      type: [Number, String],
      default: '',
      desc: '数值'
    },
    isError: {
      type: Boolean,
      default: () => true,
      desc: '是否提示'
    },
    decimalPlaces: {
      type: Number,
      default: 2,
      desc: '小数点位数'
    },
    clearable: {
      type: Boolean,
      default: true
    }
  },
  data: () => {
    return {
      tooltipModel: false,
      numberDigit: '',
      current: '',
      formatValue: '',
      errorType: false,
      unitVal: window.i18n.t('金额单位'),
      recordList: []
    }
  },
  computed: {},
  watch: {
    value(value) {
      this.calcFormatValue(value)
    }
  },
  mounted() {
    this.calcFormatValue(this.value)
  },
  methods: {
    inputCurrency(value) {
      const self = this
      value = value.toString()
      value = value.replace(/[^0-9.]/g, '')
      value = value.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3')
      const data = parseInt(value).toString()
      const moneyText = ['千', '万', '十万', '百万', '千万', '亿', '十亿', '百亿', '千亿', '万亿']
      const maxValue = 14
      if (data.length > 3 && data.length < maxValue) {
        self.tooltipModel = !this.readonly
        self.numberDigit = moneyText[data.length - 4]
      } else if (data.length > maxValue - 1) {
        value = self.value
        self.numberDigit = moneyText[moneyText.length - 1]
      } else {
        self.tooltipModel = false
        self.numberDigit = ''
      }
    },
    handleFocus() {
      // 获取焦点去掉千分位
      if (this.formatValue) {
        var x = this.formatValue.split(',')
        this.formatValue = parseFloat(x.join(''))
        this.inputCurrency(this.formatValue)
      }
    },
    handleBlur() {
      if (this.formatValue === '') {
        this.current = ''
      } else {
        let value = this.formatValue
        try {
          value = +this.formatValue.replace(/,/g, '')
        } catch {
          console.error()
        }
        if (isNaN(value)) {
          value = 0
        }
        if (this.$props.unit === 'w' && (this.unitVal === '(万)' || this.unitVal === '（万）' || this.unitVal === '(万元)' || this.unitVal === '（万元）')) {
          value *= 10000
        } else if (this.$props.unit === 'y') {
          value *= 100000000
        }
        this.$emit('cvalue', value)
        if (value > 999000000000000) {
          this.error()
          this.errorType = true
          value = this.recordList.slice(-1)
          setTimeout(() => {
            this.errorType = false
          }, 3000)
          if (value && value.length > 0) {
            if (this.$props.unit === 'rate') {
              this.current = +Number(value).toFixed(4)
            } else {
              this.current = +Number(value).toFixed(this.decimalPlaces)
            }
          } else {
            this.current = ''
          }
        } else {
          this.recordList.push(value)
          if (this.$props.unit === 'rate') {
            this.current = +Number(value).toFixed(4)
          } else {
            this.current = +Number(value).toFixed(this.decimalPlaces)
          }
        }
        this.calcFormatValue(this.current)
      }
      this.emit()
    },
    // 金额过大错误提示
    error() {
      // 多个提示标签覆盖问题.
      setTimeout(() => {
        if (this.isError) {
          this.$message({
            message: this.$t('警告，金额不能大于等于千万亿！'),
            type: 'error',
            duration: 1000
          })
        }
      })
    },
    calcFormatValue(v) {
      var value = v
      if (value > 999999999999999) {
        this.errorType = true
        this.error()
        value = this.recordList.slice(-1)
        setTimeout(() => {
          this.errorType = false
        }, 3000)
      }
      if (value === '' || value === null) {
        this.current = this.formatValue = ''
      } else {
        if (this.$props.unit === 'w' && (this.unitVal === '(万)' || this.unitVal === '（万）' || this.unitVal === '(万元)' || this.unitVal === '（万元）')) {
          value = value / 10000
        } else if (this.$props.unit === 'y') {
          value = value / 100000000
        }

        this.formatValue = this.decimalFormat(value, this.$props.unit)
      }
    },
    decimalFormat(value, unit) {
      // 强制保留4位小数
      if (unit === 'rate') {
        return value.toLocaleString('zh', { minimumFractionDigits: 4 })
      }
      if (unit === 'w' && (this.unitVal === '(万)' || this.unitVal === '（万）' || this.unitVal === '(万元)' || this.unitVal === '（万元）')) {
        return value.toLocaleString('zh', { maximumFractionDigits: this.decimalPlaces + 4 }) // 之所以加四是保留之前万元6位小数点位数
      } else if (unit === 'y' && (this.unitVal === '(亿)' || this.unitVal === '（亿）')) {
        return value.toLocaleString('zh', { maximumFractionDigits: this.decimalPlaces + 4 }) // 之所以加四是保留之前亿元6位小数点位数
      } else {
        return value.toLocaleString('zh', { maximumFractionDigits: this.decimalPlaces })
      }
    },
    emit() {
      this.$emit('input', this.current)
      this.$emit('change', this.current)
      this.tooltipModel = false
    }
  }
}
</script>
